package com.fingard.dsp.bank.directbank.gzelink01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.ReqQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.RetAtsQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.detail.RetAtsRefundDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

public class GZELINK01QryRefund extends GZELINK01Base implements IQryRefund {
    @Override
    public RetAtsQryRefund d_qry_refund(ReqQryRefund p_req) throws Exception {
        RetAtsQryRefund retAts = new RetAtsQryRefund(p_req.reqHeader);
        retAts.writeStart();

        String tmpRespCode = "";
        String tmpRespInfo = "";

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req.payAct, "");
            if (actItem == null) {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo("未找到账号[" + p_req.payAct + "]商户配置信息");
                retAts.writeEnd();
                return retAts;
            }

            int tmpSuccCount = 0;
            double tmpTotalAmt = 0;

            String[] transCodeArr = new String[]{"200003", "200004"}; // 200003为差错查询 200004为异常退汇查询
            for (int i = 0; i < transCodeArr.length; i++) {
                int tmpNowPAGE = 1;
                int tmpTotalPAGE = 1;
                boolean tmpIsNext = true;
                while (tmpIsNext) {
                    StringBuilder reqParam = new StringBuilder();
                    reqParam.append("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
                    reqParam.append("<GZELINK>");

                    reqParam.append("<INFO>");
                    reqParam.append("<TRX_CODE>" + transCodeArr[i] + "</TRX_CODE>");
                    reqParam.append("<VERSION>03</VERSION>");
                    reqParam.append("<DATA_TYPE>2</DATA_TYPE>");
                    reqParam.append("<REQ_SN>" + p_req.reqHeader.transSeqID + "</REQ_SN>");
                    reqParam.append("<USER_NAME>" + actItem.userCode + "</USER_NAME>");
                    reqParam.append("<USER_PASS>" + actItem.userFlag + "</USER_PASS>");
                    reqParam.append("<SIGNED_MSG></SIGNED_MSG>");
                    reqParam.append("</INFO>");

                    reqParam.append("<BODY>");
                    reqParam.append("<QUERY_TRANS>");
                    reqParam.append("<MERCHANT_ID>" + actItem.merchantId + "</MERCHANT_ID>");
                    reqParam.append("<QUERY_SN></QUERY_SN>");
                    reqParam.append("<BEGIN_DATE>" + Format.Date8Format.format(p_req.getQryStartDate()) + "</BEGIN_DATE>");
                    reqParam.append("<END_DATE>" + Format.Date8Format.format(p_req.getQryEndDate()) + "</END_DATE>");
                    reqParam.append("<PAGE_NUM>1</PAGE_NUM>");
                    reqParam.append("<QUERY_REMARK></QUERY_REMARK>");
                    reqParam.append("</QUERY_TRANS>");
                    reqParam.append("</BODY>");

                    reqParam.append("</GZELINK>");

                    String waitSignData = reqParam.toString().replaceAll("<SIGNED_MSG></SIGNED_MSG>", "");
                    WriteBankLogLn2("待签名数据:\r\n" + waitSignData);

                    String signature = signMsg(waitSignData, actItem);

                    String reqData = reqParam.toString().replaceAll("<SIGNED_MSG></SIGNED_MSG>", "<SIGNED_MSG>" + signature + "</SIGNED_MSG>");
                    WriteBankLogStep2(reqData);

                    String[] tmpRetStr = sendDataToGZE(reqData, bankFront.getUrl("generalRecPay"));
                    
                    if(tmpRetStr[0].length() == 0) {
                    	WriteBankLogStep3(tmpRetStr[1]);
                    	
                    	StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);

                        if (tmpBkReader != null) {
                            tmpRespCode = "0";

                            String tmpRetCode = tmpBkReader.getFirstText("/GZELINK/INFO/RET_CODE");
                            if ("0000".equals(tmpRetCode)) {
                                String totalPageNum = tmpBkReader.getFirstText("/GZELINK/BODY/QUERY_TRANS/PAGE_SUM");
                                if (StringHelper.hasAnyChar(totalPageNum)) {
                                    tmpTotalPAGE = Integer.parseInt(totalPageNum);
                                } else {
                                    tmpTotalPAGE = 0;
                                    tmpIsNext = false;
                                }
                                if (tmpNowPAGE >= tmpTotalPAGE) {
                                    tmpIsNext = false;
                                } else {
                                    tmpNowPAGE++;
                                }

                                while (tmpBkReader.read("/GZELINK/BODY/RET_DETAILS/RET_DETAIL")) {
                                    String oriState = tmpBkReader.readedXElement.getSingleText("ORI_STATE");
                                    String adjState = tmpBkReader.readedXElement.getSingleText("ADJ_STATE");
                                    if ("0".equals(oriState) && "1".equals(adjState)) {
                                        RetAtsRefundDetail tmpRetDetail = new RetAtsRefundDetail();

                                        String sn = tmpBkReader.readedXElement.getSingleText("SN");
                                        if (StringHelper.hasAnyChar(sn)) {
                                            tmpRetDetail.reqBatchNO = tmpBkReader.readedXElement.getSingleText("REQ_SN");
                                            tmpRetDetail.askNum = sn;
                                        } else {
                                            tmpRetDetail.askNum = tmpBkReader.readedXElement.getSingleText("REQ_SN");
                                        }
                                        tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("ACCOUNT");
                                        tmpRetDetail.recActName = tmpBkReader.readedXElement.getSingleText("ACCOUNT_NAME");
                                        tmpRetDetail.amount = StringHelper.amountDivide100(tmpBkReader.readedXElement.getSingleText("AMOUNT"));
                                        tmpRetDetail.refundTicketDate = Format.Date10Format.format(Format.Date8Format.parse(tmpBkReader.readedXElement.getSingleText("ADJ_DATE")));
                                        tmpRetDetail.refundTicketReason = tmpBkReader.readedXElement.getSingleText("ADJ_MSG");
                                        tmpRetDetail.submitTime = Format.DateTimeFormat.format(Format.Date8Format.parse(tmpBkReader.readedXElement.getSingleText("ADJ_DATE")));

                                        tmpSuccCount++;
                                        tmpTotalAmt += Double.parseDouble(tmpRetDetail.amount);

                                        retAts.writeRetDetail(tmpRetDetail);
                                    } else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "原交易状态和调整后状态不符合退票要求";
                                    }
                                }
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpBkReader.getFirstText("/GZELINK/INFO/ERR_MSG");
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                        }
                    } else {
                    	tmpRespCode = "-1"; 
                    	tmpRespInfo = tmpRetStr[1];
                    }
                }
            }

            if (tmpSuccCount > 0) {
                retAts.totleAmount = StringHelper.amountDivide100(String.valueOf(tmpTotalAmt));
                retAts.totleNum = String.valueOf(tmpSuccCount);
            }
        } catch (Exception ex) {
            ex.printStackTrace();

            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();

            WriteBankLogLn(ex);
        }

        if (tmpRespCode.equals("-1")) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }

        retAts.writeEnd();
        return retAts;
    }
}
